<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box img{
      width: 80px;
    }
  </style>
</head>
<body>

  <div id="box"></div>
  <script>
    function TrafficLight(){
      this.color = 1;
      this.init();
      this.bindEvent();
    }

    // 初始化
    TrafficLight.prototype.init = function(){
      this.dom = document.createElement('img');
      this.dom.src = "./images/" + this.color + '.jpg';
      box.appendChild(this.dom);
    }

    // 监听事件
    TrafficLight.prototype.bindEvent = function(){
      // 备份上下文,这里的this指的是JS实例
      var self = this;
      // 当自己的dom被点击的时候
      this.dom.onclick = function() {
        // 当被点击的时候，调用自己的changeColor方法
        self.changeColor();
      }
    }

    // 改变颜色
    TrafficLight.prototype.changeColor = function(){
      this.color ++;
      if(this.color == 4){
        this.color = 1;
      }
      this.dom.src = "./images/" + this.color + ".jpg";
    };

    var box = document.getElementById('box');
    var count = 100;
    while(count--) {
      new TrafficLight();
    }

  </script>
</body>
</html>